package com.newsmanagement.service.impl;

import com.newsmanagement.common.Constants;
import com.newsmanagement.dao.IFileServiceDao;
import com.newsmanagement.entity.ReturnedMessages;
import com.newsmanagement.service.IFileService;
import com.newsmanagement.util.CheckAndChangeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;

/**
 * @author xbr
 * 2017/12/4 16:29
 * 角色管理service实现
 */
@Service
@Transactional
public class FileServiceImpl implements IFileService {


    @Autowired
    private IFileServiceDao fileServiceDao;

    /**
     * 上传文件信息
     * @param request
     * @param file 上传文件
     * @param upFilePath 存放文件的上几级文件路径
     * @return ReturnedMessages
     */
    @Override
    public ReturnedMessages uploadFile(HttpServletRequest request , MultipartFile file ,String upFilePath){
        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证用户id
        if(null == file){
            return returnedMessages.ReturnedMessagesFail(500 ,"请选择文件");
        }

        //文件名称
        String fileName = file.getOriginalFilename();

        //保存文件的上级路径获取
        String filePath = request.getSession().getServletContext().getRealPath("/") + upFilePath;
        CheckAndChangeUtil.getFolderCreateFolder(filePath);

        //文件路径
        filePath = filePath + fileName;

        try {
            //转存文件
            file.transferTo(new File(filePath));

        }catch (Exception e) {
            return returnedMessages.ReturnedMessagesFail(500 ,"文件存储异常");
        }

        //保存文件信息
        fileServiceDao.addFile(fileName ,upFilePath + fileName);
        return returnedMessages;
    }

}
